var turing = window["tg-turing"];
var params = turing.utils.getUrlParam();
var defId = params.defId;
var needNextNode = urlParamToBoolean(params, 'needSelectNode');
var needNextAssignees = urlParamToBoolean(params, 'needSelectAssignees');
var oneLegKicking = urlParamToBoolean(params, 'oneLegKicking');
/**
 * urlParamToBoolean url参数值（"true"/"false"）转化为布尔值
 */
function urlParamToBoolean(params, name) {
    return params[name] === 'true' ? true : false;
}
//如果页面是查看详情进来的页面，将页面不能点击
//if (window.location.href.indexOf('operStatus=1') > -1) {
//    document.body.classList.add('ybt-form-readonly');
//}
if(formReadOnly){
	document.body.classList.add('ybt-form-readonly');
}

YBTFORM.init();

var isMuiltpart = false;
var URLArr = [{
    value: 'start',
    url: '/sys/emapflow/tasks/startFlow.do'
}, {
    value: 'submit',
    url: '/sys/emapflow/tasks/execute.do'
}, {
    value: 'draft',
    url: '/sys/emapflow/tasks/startFlow.do'
}, {
    value: 'turnback',
    url: '/sys/emapflow/tasks/turnback.do'
}, {
    value: 'processStatus',
    url: '/sys/emapflow/tasks/queryFlowState.do'
}, {
    value: 'changeAssignee',
    url: '/sys/emapflow/tasks/changeAssignee.do'
}, {
    value: 'callback',
    url: '/sys/emapflow/tasks/callback.do'
}, {
    value: 'termination',
    url: '/sys/emapflow/tasks/terminateInstance.do'
}];

(function(d) {
    if (navigator.userAgent.indexOf('MSIE 9') === -1) return;

    d.addEventListener('selectionchange', function() {
        var el = d.activeElement;

        if (el.tagName === 'TEXTAREA' || (el.tagName === 'INPUT')) {
            var ev = d.createEvent('CustomEvent');
            ev.initCustomEvent('input', true, true, {});
            el.dispatchEvent(ev);
        }
    });
})(document);


function _getValidateRules(field, rules) {
    if (field.required === false || field.readonly === true) {
        return;
    }
    if (field.required !== undefined && field.hidden !== true) {
        if (rules[field.name] === undefined) {
            rules[field.name] = [];
        }
        // 区分单选/多选 select校验
        if (field.xtype == 'select' && field.multiple == true) {
            field.xtype = 'multi-select';
        }
        var xtype = turing.defaults["antd"].form[field.xtype || "static"];
        if (field.xtype == 'checkboxlist') {
            //            xtype.required.type = 'string';
        }
        if (xtype !== undefined) {
            var required = xtype.required;
            if (required !== undefined) {
                // required.required = true;
                var ctl = {
                    required: field.required
                };
                if (field.dataType !== undefined) {
                    var type = "string";
                    if (required.type === undefined) {
                        ctl["type"] = type;
                    }
                }
                switch (field.xtype) {
                    case "date-local":
                    case "datetime":
                        ctl["type"] = "string";
                        break;
                    case "uploadfile":
                        ctl["type"] = "object";
                        break;
                }
                //将需要验证string类型的字段值，都设定为字符串，以便校验格式通过
                if (this.formData[field.name] === undefined || this.formData[field.name] === null) {
                    //  debugger;
                    // this.formData[field.name]="1";
                } else {
                    this.formData[field.name] = String(this.formData[field.name]);
                }
                var resultRule = Object.assign({}, {
                    field: field
                }, required, ctl);
                rules[field.name].push(resultRule);
                //额外的校验规则
                if (field.checkrule) {
                    var extraRule = JSON.parse(JSON.stringify(resultRule));
                    extraRule.type = 'string';
                    switch (field.checkrule) {
                        case 'email':
                            extraRule.message = '邮箱格式不正确';
                            extraRule.pattern = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
                            break;
                        case 'idcard':
                            extraRule.message = '身份证格式不正确';
                            extraRule.pattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
                            break;
                        case 'phone':
                            extraRule.message = '电话格式不正确';
                            extraRule.pattern = /^1[34578]\d{9}$/;
                            break;
                        default:
                            extraRule.message = '格式不正确';
                            break;
                    }
                    rules[field.name].push(extraRule);
                }
            }
        }
    }

    if (field.dataSize !== undefined && field.hidden !== true) {
        if (rules[field.name] === undefined) {
            rules[field.name] = [];
        }
        var max = Number(field.dataSize);
        if (max > 0) {
            rules[field.name] = rules[field.name].concat(Object.assign({}, {
                field: field
            }, {
                max: max,
                message: '内容太长，不能超过 ' + max
            }));
        }
    }
}


var rules = {}
turing.utils.extend(formDefineJSON.data.formData, formData);
//格式化初始值
formDefineJSON.data.formData = turing.EMAP.deserialize(formDefineJSON.data.formData, formDefineJSON.data.emapConfig);
var isshowtoolbar = {};
for (var i = 0; i < meta.length; i++) {
    var key = meta[i].name;
    // debugger;
    meta[i].formReadonly = formReadOnly || (formDefineJSON.data.emapConfig[key] && formDefineJSON.data.emapConfig[key].readonly);
    if (meta[i].dataType === "Clob") {
        isMuiltpart = true;
    }
    if (meta[i].url !== undefined) {
        meta[i].dict = {
            url: meta[i].url
        }
    }
    if (meta[i].ref !== undefined) {
        meta[i].readonly = formReadOnly;
        if (meta[i].manageSub) {
            isshowtoolbar[key] = meta[i].manageSub;
        } else {
            isshowtoolbar[key] = "";
        }
        meta[i].ref = meta[i].ref.map(function(item) {
            if (item.url !== undefined) {
                item.dict = {
                    url: item.url
                }
            }
            item.key = item.title = item.name;
            item.minWidth = 120;
            item.ellipsis = true;
            item.tooltip = true;
            return item;
        });
    }

    formDefineJSON.data.emapConfig[key] = turing.utils.extend(true, {}, meta[i], {
        model: meta[i]
    }, formDefineJSON.data.emapConfig[key]);
    //处理主表数据中的日期类型
    if (meta[i].dataType === "Timestamp") {
        var targetItem = formDefineJSON.data.emapConfig[key];
        changeDateStyle(targetItem, meta[i]);
    }
    //处理子表数据中的日期类型,只修改模型内的参数未重新保存表单的情况 add by jbxu 2019-04-01
    var metaRef = meta[i].ref;
    if (metaRef && metaRef.length > 0) {
        metaRef.forEach(function(item, index) {
            var targetItem = formDefineJSON.data.emapConfig[key].ref[index];
            changeDateStyle(targetItem, item);
        });
    }

    function changeDateStyle(obj, param) {
        if (param.dataType === "Timestamp") {
            switch (param.format) {
                case 'yyyy-MM':
                    obj.type = 'month';
                    obj.xtype = 'date-ym';
                    obj.format = 'yyyy-MM';
                    break;
                case 'yyyy-MM-dd HH:mm:ss':
                    obj.type = 'datetime';
                    obj.xtype = 'date-local';
                    obj.format = 'yyyy-MM-dd HH:mm:ss';
                    break;
                default:
                    obj.type = 'date';
                    obj.xtype = 'date';
                    obj.format = param.format;
                    break;
            }
        }
    }
    _getValidateRules(formDefineJSON.data.emapConfig[key], rules);
}

for (var prop in formDefineJSON.data.defaultConfig) {
    if (formData[prop] === undefined) {
        formData[prop] = formDefineJSON.data.defaultConfig[prop];
    }
}

// iframe 获取结果的处理
function dealWithContent(iframe) {
    var content = iframe.contentWindow.document.body.innerHTML;
    content = content.match(/{.*}/g) ? content.match(/{.*}/g)[0] : null;
    if (content) {
        var data = JSON.parse(content);
        if (data.succeed) {
            window.iview.Message.success('操作成功！');
            window.parent.postMessage({
                'type': 'EMAP_FLOW_CLOSE'
            }, '*');
            setTimeout(function() {
//              window.close();
            	YBTFORM.service.record($("#ybtFormBljl")[0], false, "todo")
          }, 1000);
        } else {
            window.iview.Message.error('操作失败');
        }
    }else{
    	window.iview.Message.error('操作失败');
    }
}

// 监听表单上传接口返回信息iframe（#upload_pipe）的内容
var iframe = document.getElementById('upload_pipe');
if (iframe.attachEvent) {
    iframe.attachEvent("onload", function() {
        dealWithContent(iframe)
    });
} else {
    iframe.onload = function() {
        dealWithContent(iframe)
    };
}

//处理在设计态时label文字是一行展示，但到运行态时label出现换行
$('.appFont').each(function() {
    var $td = $(this).closest('td');
    $td.css('box-sizing', 'content-box');
});

var app = new Vue({
    el: '#app',
    data: function() {
        return Object.assign(formDefineJSON.data, {
            "debug": params.debug === "true",
            "hasHistory": window.history.length > 1,
            "defid": defId,
            "defkey": defKey,
            "taskId": taskId,
            "action": submitURL,
            "flowComment": {
                "flowComment": "",
                "elecsealUrl": ''
            },
            "showCurComment": !formReadOnly,
            "showNextNode": needNextNode,
            "showNextAssignees": needNextAssignees,
            "oneLegKicking": oneLegKicking,
            "nextAssignees": {},
            "customNextAssignees": [], //下一步办理人组件 -- 自定义展示选中人办理人数据
            "formReadOnly": formReadOnly, //表单是否只读
            "rules": rules,
            "multipart_data": undefined,
            "isshowtoolbar": isshowtoolbar,
            "usedmeta": sameFormExt.usedmeta,
            "messageType": [], //催办类型
        })
    },
    computed: {
        flowCommentWidth: function() {
            var style = document.getElementsByClassName('ybt-design-pc')[0].style
            var width = style.width;
            var padding = style.paddingLeft;
            if (!padding) {
                return width
            } else {
                return parseInt(width.slice(0, -2)) - parseInt(padding.slice(0, -2)) * 2 + "px";
            }
        },
        processedFormData: function() {
            return turing.EMAP.serialize(this.formData, this.emapConfig);
        },
    },
    watch: {
        formData: {
            handler: function(val) {
                // debugger;
                DoExpressionCompute.apply(this);
            },
            immediate: true,
            deep: true
        }
    },
    methods: {
        elecsealSelectOk: function() {},
        elecsealSelectCancel: function() {},
        elecsealSelectShow: function() {},
        goback: function() {
            window.history.go(-1);
        },
        closeWindow: function() {
            window.close();
        },
        onFormDataChange: function(name, value, display, model, subgrid) {
            if (subgrid !== undefined) {
                var index = subgrid.index;
                var row = subgrid.row;
                if (this.formData[subgrid.name] === undefined || this.formData[subgrid.name] === null) {
                    this.$set(this.formData, subgrid.name, [])
                }
                if (index !== undefined) {
                    if (this.formData[subgrid.name][index] === undefined) {
                        this.formData[subgrid.name].push(row); //新增操作
                    } else {
                        this.$set(this.formData[subgrid.name][index], name, value) //修改操作
                    }
                } else {
                    //删除操作，不做处理
                }
            } else {
                // 2019-06-27 去掉判断数组，因为PC checkbox校验会存在问题
                // if (Array.isArray(value)) {
                //     this.$set(this.formData, name, value.join(','));
                // } else {
                this.$set(this.formData, name, value);
                // }
            }

            this.checkDoUpdateNextStepPerson(name, value);
        },
        checkDoUpdateNextStepPerson: function(name, value) {
            var usedmeta = sameFormExt.usedmeta;
            if (usedmeta) {
                var count = usedmeta.length;
                for (var i = 0; i < count; i++) {
                    var usedItem = usedmeta[i];
                    if (usedItem.name === name) {
                        if (usedItem.updateNextStepPerson === true) {
                            this.doUpdateNextStepPerson(name, value, this.formData);
                        }
                        break;
                    }
                }
            }
        },
        doUpdateNextStepPerson: function(name, value, formData) {
            this.$refs.nextStep.linkFormChange(formData);
        },
        submit: function() {
            var that = this;
            turing.EMAP.serialize(this.formData, this.emapConfig);
            this.$refs["form"].validate(function(valid) {
                if (valid) {
                    if (isMuiltpart === true) {
                        that.$refs.multipart_data.value = JSON.stringify(that.formData);
                        that.$refs.multipart_form.submit();
                        that.$refs.multipart_data.value = "";
                    } else {
                        turing.utils.Post(submitURL, {
                            data: JSON.stringify(that.formData)
                        }).then(function(result) {
                            if (result.data.code === "0") {
                                window.iview.Message.success('保存成功');
                            } else {
                                window.iview.Message.error('保存失败');
                            }
                        });
                    }
                }
            })
        },
        onverify: function(item) {
            // 合并下一步办理人组件数据
            Object.assign(item, this.nextAssignees);
            var that = this;
            var emapFlowToolbar = this.$refs["emapFlowToolbar"];
            var formNode = this.$refs["multipart_form"];
            // 获取当前item的url
            if (!item.url) {
                var currentUrl = URLArr.filter(function(obj) {
                    return obj.value === item.commandType
                });
                item.url = currentUrl[0].url;
            }
            // 跳过自定义的命令按钮
            var canPassCommandType = ["processStatus", "urgent", "addAssigneeTask", "deleteAssigneeTask","processTrack"];
            if (canPassCommandType.indexOf(item.commandType) > -1) {
                return true;
            }
            // 判断this.formData是否为空对象，空对象直接跳出
            if (this.isEmptyObject(this.formData)) {
                window.iview.Message.error('没有可提交的表单！');
                return false
            }
            // 存在文件上传时，处理form数据
            if (isMuiltpart === true) {
                //判断上传组件是否通过校验
                if (!that.$refs["ybtupload"].validate()) {
                    return;
                }
                formNode.action = contextPath + item.url;
                var nodes = formNode.childNodes;
                for (var i = nodes.length - 1; i >= 0; i--) {
                    var node = nodes[i];
                    formNode.removeChild(node);
                }
                var obj = item;
                var formDataCopy = turing.EMAP.serialize(that.formData, that.emapConfig);
                formDataCopy.elecseal = this.flowComment.elecsealUrl;
                obj.formData = JSON.stringify(formDataCopy);
                obj.taskId = taskId;
                obj.defKey = defKey;
                obj.flowComment = this.flowComment.approval ?
                    (this.flowComment.approval + (this.flowComment.flowComment ? "," + this.flowComment.flowComment : "")) :
                    this.flowComment.flowComment;
                var input;
                for (var key in obj) {
                    input = document.createElement('input');
                    input.type = "hidden";
                    input.name = key;
                    input.value = obj[key];
                    formNode.appendChild(input);
                }
            }
            // 校验审批意见
            if (this.$refs.emapFlowComment) {
                var emapFlowCommentValid = this.$refs.emapFlowComment.validate();
                if (!emapFlowCommentValid) return
            }
            // 启动、提交 情况下，校验下一步节点、下一步办理人
            if (item.id === 'start' || item.id === 'submit') {
                var valid = this.$refs.nextStep.validate();
                if (!valid) return
            }
            // 保存草稿时，跳过验证;流程转办，弹出Modal获取assignee参数
            if (item.commandType === 'draft') {
                if (isMuiltpart === true) {
                    formNode.submit();
                } else {
                    emapFlowToolbar[item.execute](item);
                }
            } else if (item.commandType === 'changeAssignee') {
                // 流程转办,特殊处理，弹出Model层,表单只读不需要校验
                if (this.formReadOnly || this.isEmptyObject(this.rules)) {
                    return true
                } else {
                    this.$refs["form"].validate(function(valid) {
                        if (valid) {
                            emapFlowToolbar[item.execute](item);
                        }
                    });
                }
            } else {
                if (this.formReadOnly || this.isEmptyObject(this.rules)) {
                    if (isMuiltpart === true) {
                        formNode.submit();
                    } else {
                        emapFlowToolbar[item.execute](item);
                    }
                    emapFlowToolbar.buttons.map(function(btn, index) {
                        if (btn.id === item.id) {
                            btn.disabled = true;
                        }
                        return btn
                    });
                    emapFlowToolbar.$set(emapFlowToolbar.buttons);
                } else {
                    this.$refs["form"].validate(function(valid) {
                        if (valid) {
                            if (isMuiltpart === true) {
                                formNode.submit();
                            } else {
                                emapFlowToolbar[item.execute](item);
                            }
                            emapFlowToolbar.buttons.map(function(btn, index) {
                                if (btn.id === item.id) {
                                    btn.disabled = true;
                                }
                                return btn
                            });
                            emapFlowToolbar.$set(emapFlowToolbar.buttons);
                        }
                    });
                }
            }
        },
        /**
         * <转办命令> 是否存在文件上传进行二次校验
         */
        fileexistverify: function(item) {
            if (isMuiltpart === true) {
                var formNode = this.$refs["multipart_form"];
                var input = document.createElement('input');
                input.type = "hidden";
                input.name = "assignee";
                input.value = item.assignee;
                formNode.appendChild(input);
                formNode.submit();
                return true;
            }
        },
        /**
         * emapFlowToolbar按钮动作数据
         */
        onbtnrender: function(btns, e) {
            var result = btns.map(function(btn) {
                btn.alias = params.alias;
                return btn
            });
            return result
        },
        action_complete: function(type, data) {
            if (type !== "processStatus" && type !== "process_track") {
                if (data.data.succeed) {
                    window.iview.Message.success('操作成功！');
                    window.parent.postMessage({
                        'type': 'EMAP_FLOW_CLOSE'
                    }, '*');
                    setTimeout(function() {
                    	if(YBTFORM.service){
                    		YBTFORM.service.record($("#ybtFormBljl")[0], false, "doing")
                    	}else{
                    		window.close();
                    	}
                    }, 1000);
                } else {
                    window.iview.Message.error('操作失败！');
                }
            }
        },
        // 审批意见组件 -- 选项变更
        approvalChange: function(value, field) {
            this.formData[field] = value;
            this.checkDoUpdateNextStepPerson(field, value);
        },
        // 空对象判断
        isEmptyObject: function(obj) {
            for (var key in obj) {
                return false;
            }
            return true;
        }
    },
    mounted: function() {
        var self = this;
        // 获取催办方式
        turing.utils.Post(contextPath + '/sys/emapflow/*default/queryMessageTypeConfig.do').then(function(res) {
            if (res.data && res.data.messageType) {
                self.messageType = res.data.messageType.map(function(item) {
                    item.value = item.code;
                    item.label = item.name;
                    return item;
                });
            }
        });
        //动态iframe高度
        var wrapperHeight = document.documentElement.clientHeight - 78;
        $("#pc_menu_iframe").height(wrapperHeight);
        //计算总值
    	DoExpressionCompute.apply(this);
        window._emapShowFormVue = this;
    }
})

//判断是否显示服务管理
//showServiceManage();
function showServiceManage(){
	var index = defKey.lastIndexOf(".");
	var app_name = defKey.substring(0, index);
    var url = contextPath + "/sys/eetableservice/singleService/isServiceAdmin.do";
    var params = {
		appname: app_name,
    }
	$.ajax({
        type: "POST",
        url: url,
        data: params,
        dataType: "json",
        success: function(resp){
        	if (resp.code == 0) {
        		if(resp.datas.isServiceAdmin){
        			$("#ybtFormServiceManage").show();
        		}else{
        			$("#ybtFormServiceManage").hide();
        		}
            } else {
            	iview.Message.error('查询是否服务管理员失败');
            }
        },
        error: function(e){
        	iview.Message.error(e);
        }
    });
}